package com.aizhixin.lab.task.service;

import java.util.*;

import com.aizhixin.lab.task.entity.*;
import com.aizhixin.lab.task.repository.TaskStuCodeRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.aizhixin.lab.account.dto.AccountDTO;
import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.course.template.service.TemplateAssistService;
import com.aizhixin.lab.task.core.ExerciseType;
import com.aizhixin.lab.task.core.TaskInforCode;
import com.aizhixin.lab.task.domain.TaskFileDomain;
import com.aizhixin.lab.task.domain.TaskQuestionChoiceDomain;
import com.aizhixin.lab.task.domain.TaskQuestionDomain;
import com.aizhixin.lab.task.repository.TaskQuestionRepository;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Transactional
@Service
public class TaskQuestionsService {
    @Autowired
    private TaskQuestionRepository questionRespository;
    @Autowired
    private TaskService taskService;
    @Autowired
    private TaskFileService taskFileService;
    @Autowired
    private TaskQuestionJDBC taskQuestionJDBC;
    @Autowired
    private TaskQuestionChoiceService taskQuestionChoiceService;
    @Autowired
    private TaskStuCodeRepository taskStuCodeRepository;

    /**
     * @param @param  domain
     * @param @param  dto
     * @param @return
     * @return TaskQuestion
     * @throws
     * @Title: saveQuestions
     * @Description: 保存试题
     */
    public Map<String, Object> saveQuestionList(List<TaskQuestionDomain> domainList,AccountDTO dto){
        Map<String, Object> result = new HashMap<String, Object>();
        for (int i = 0; i < domainList.size(); i++) {
            if (domainList.get(i).getTaskId().isEmpty()) {
                result.put(ApiReturnConstants.SUCCESS, false);
                result.put(ApiReturnConstants.ERROR, "任务id不能为空！");
                return result;
            }
            boolean isFileEmpty = false;
            if (domainList.get(i).getAccessorylist().isEmpty()) {
                isFileEmpty = true;
            }
            if (StringUtils.isEmpty(domainList.get(i).getAnswer())){
                result.put(ApiReturnConstants.SUCCESS, false);
                int a = i+ 1;
                result.put(ApiReturnConstants.ERROR, "第"+a +"题 答案不能为空！");
                return result;
            }
            if (domainList.get(i).getQuestionContent().isEmpty() && !isFileEmpty) {
                result.put(ApiReturnConstants.SUCCESS, false);
                int a = i+ 1;
                result.put(ApiReturnConstants.ERROR, "第"+a+"题 题目题干和题干附件不能同时为空！");
                return result;
            }
            if((ExerciseType.MULTIPLE.getIntValue().equals(domainList.get(i).getQuestionType()) || ExerciseType.SINGLE.getIntValue().equals(domainList.get(i).getQuestionType()))&&domainList.get(i).getChoicelist()==null){
                result.put(ApiReturnConstants.SUCCESS, false);
                int a = i+ 1;
                result.put(ApiReturnConstants.ERROR, "第"+a+"题 客观题选项不能够为空！");
                return result;
            }
            Task byId = taskService.findById(domainList.get(i).getTaskId());
            if (byId==null){
                result.put(ApiReturnConstants.SUCCESS, false);
                result.put(ApiReturnConstants.ERROR, "任务不存在");
                i++;
                return result;
            }
            //如果题目类型为编程题选择题则必须传语言类型
            if (domainList.get(i).getQuestionType() == 60 && domainList.get(i).getLanguage() == null){
                result.put(ApiReturnConstants.SUCCESS, false);
                int a = i+ 1;
                result.put(ApiReturnConstants.ERROR, "第"+a+"题 语言种类必须选择！");
                i++;
                return result;
            }
        }

        TaskQuestionDomain taskQuestionDomain = domainList.get(0);
        Task task = taskService.findById(taskQuestionDomain.getTaskId());
        if (Objects.isNull(task)){
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "找不到该任务");
            return result;
        }
        task.setQuestionsNum(0);
        taskService.save(task);
        questionRespository.deleteByTaskId(taskQuestionDomain.getTaskId());
        for (TaskQuestionDomain domain:domainList){
            saveQuestions(domain,dto);
        }
        result.put(ApiReturnConstants.SUCCESS,true);
        result.put(ApiReturnConstants.DATA,"保存成功");
        return result;
    }

    public TaskQuestion saveQuestions(TaskQuestionDomain domain, AccountDTO dto) {
        TaskQuestion questions = new TaskQuestion();
        questions.setId(UUID.randomUUID().toString());
        questions.setTaskId(domain.getTaskId());
        questions.setQuestionContent(domain.getQuestionContent());
        questions.setAnalysis(domain.getAnalysis().trim());
        questions.setAnswer(domain.getAnswer());
        questions.setCreatedBy(dto.getId());
        questions.setQuestionType(domain.getQuestionType());
        questions.setLanguage(domain.getLanguage());
        questions.setReferenceCode(domain.getReferenceCode());
        questions.setKeyword(domain.getKeyword());

        TaskQuestion selectedquestions = this.findById(domain.getSelectedQuestionId());
        
        if (null != selectedquestions) {
            questions.setOrderNum(selectedquestions.getOrderNum() + 1);
            taskQuestionJDBC.updateOrderNum(selectedquestions.getTaskId(), selectedquestions.getOrderNum());
        } else {
        	Integer questionNum=taskQuestionJDBC.countByTaskIdAndDeleteFlag(domain.getTaskId(),DataValidity.VALID.getState());
        	if(questionNum>0){
        		 questions.setOrderNum(questionNum+1);
        	}else{
        		 questions.setOrderNum(1);
        	}
        }
        saveAccessory(domain, dto, questions);
        
        if(ExerciseType.MULTIPLE.getIntValue().equals(domain.getQuestionType()) || ExerciseType.SINGLE.getIntValue().equals(domain.getQuestionType())||ExerciseType.JUDGMENT.getIntValue().equals(domain.getQuestionType())) {
        	saveChoice(domain, questions.getId());
        }
        
        TaskQuestion taskQuestion = questionRespository.save(questions);
        
        Task task = taskService.findById(domain.getTaskId());
        if(null != task){
        	task.setQuestionsNum(task.getQuestionsNum()+1);
        	taskService.save(task);
        }
        
        return taskQuestion;
    }

    /**
     * 保持试题附件
     * @param domain
     * @param dto
     * @param questions
     */
    @Async
	public void saveAccessory(TaskQuestionDomain domain, AccountDTO dto,
			TaskQuestion questions) {
        List<TaskFileDomain> questionsAccessoryDomainList=new ArrayList<>();
        //附件文件所属来源[question:题干,choice:选项,answer:答案,analysis:解析
        if (!domain.getAccessorylist().isEmpty()){
            for (TaskFileDomain questionsAccessoryDomain:domain.getAccessorylist()){
                questionsAccessoryDomain.setSource(TaskInforCode.FILE_FROM_QUESTION);
                questionsAccessoryDomainList.add(questionsAccessoryDomain);
            }
        }
        if (!domain.getAccessorylistAnswer().isEmpty()){
            for (TaskFileDomain questionsAccessoryDomain:domain.getAccessorylistAnswer()){
                questionsAccessoryDomain.setSource(TaskInforCode.FILE_FROM_ANSWER);
                questionsAccessoryDomainList.add(questionsAccessoryDomain);
            }
        }
        if (!domain.getAccessorylistAna().isEmpty()){
            for (TaskFileDomain questionsAccessoryDomain:domain.getAccessorylistAna()){
                questionsAccessoryDomain.setSource(TaskInforCode.FILE_FROM_ANALYSIS);
                questionsAccessoryDomainList.add(questionsAccessoryDomain);
            }
        }
		if (null != questionsAccessoryDomainList && 0 < questionsAccessoryDomainList.size()) {
			List<TaskFile> questionsAccessorys=new ArrayList<>();
            for (TaskFileDomain accessoryDomain : questionsAccessoryDomainList) {
            	TaskFile accessory = new TaskFile();
                accessory.setId(UUID.randomUUID().toString());
                accessory.setTaskId(domain.getTaskId());
                accessory.setTaskQuestionId(questions.getId());
                accessory.setTaskChoiceId(accessoryDomain.getTaskChoiceId());
                accessory.setSource(accessoryDomain.getSource());
                accessory.setFileName(accessoryDomain.getFileName());
                accessory.setFileUrl(accessoryDomain.getFileUrl());
                accessory.setFileKey(accessoryDomain.getFileKey());
                accessory.setOrderNum(accessoryDomain.getOrderNum());
                questionsAccessorys.add(accessory);
            }
            if(!questionsAccessorys.isEmpty()){
            	taskFileService.saveList(questionsAccessorys);
            }
        }
	}
	
	/**
	 * 保存试题选项和附件
	 * @param domain
	 * @param
	 * @param
	 */
	@Async
	public void saveChoice(TaskQuestionDomain domain, String questionId) {
		if (null != domain.getChoicelist() && 0 < domain.getChoicelist().size()) {
			List<TaskFile> fileList = new ArrayList<TaskFile>();
			List<TaskQuestionChoice> choiceList = new ArrayList<TaskQuestionChoice>();
            for (TaskQuestionChoiceDomain choiceDomain : domain.getChoicelist()) {
            	TaskQuestionChoice choice = new TaskQuestionChoice();
            	String choiceId =UUID.randomUUID().toString();
            	choice.setId(choiceId);
            	choice.setOption(choiceDomain.getOption());
            	choice.setChoiceContent(choiceDomain.getChoiceContent());
            	choice.setTaskQuestionId(questionId);
            	choiceList.add(choice);
            	if(!choiceDomain.getAccessorylist().isEmpty()) {
            		  for (TaskFileDomain accessoryDomain : choiceDomain.getAccessorylist()) {
                      	TaskFile accessory = new TaskFile();
                          accessory.setId(UUID.randomUUID().toString());
                          accessory.setTaskId(domain.getTaskId());
                          accessory.setTaskQuestionId(questionId);
                          accessory.setTaskChoiceId(choiceId);
                          accessory.setSource(TaskInforCode.FILE_FROM_CHOICE);
                          accessory.setFileName(accessoryDomain.getFileName());
                          accessory.setFileUrl(accessoryDomain.getFileUrl());
                          accessory.setFileKey(accessoryDomain.getFileKey());
                          accessory.setOrderNum(accessoryDomain.getOrderNum());
                          fileList.add(accessory);
                      }
            	}
           
            }
            taskQuestionChoiceService.saveChoiceList(choiceList);
            if(!fileList.isEmpty()) {
            	taskFileService.saveList(fileList);
            }
        }
	}
    /**
     * @param   domain
     * @param   dto
     * @param   questions 
     * @return TaskQuestion
     * @throws
     * @Title: updateQuestions
     * @Description: 修改试题
     */
    @Transactional
    public TaskQuestion updateQuestions(TaskQuestionDomain domain, AccountDTO dto, TaskQuestion questions) {
        questions.setQuestionContent(domain.getQuestionContent());
        questions.setAnalysis(domain.getAnalysis());
        questions.setAnswer(domain.getAnswer());
        questions.setQuestionType(domain.getQuestionType());
        questions.setLanguage(domain.getLanguage());
        questions.setReferenceCode(domain.getReferenceCode());
        List<TaskFile> accessorylist = taskFileService.findAllByTaskQuestionId(domain.getId());
        List<TaskFile> deleteAccessoryList=new ArrayList<>();
        List<TaskFileDomain> addAccessoryList=new ArrayList<>();
        for (TaskFile accessory : accessorylist) {
        	boolean isExct=false;
        	for (int i = 0; i < domain.getAccessorylist().size(); i++) {
        		if(null==domain.getAccessorylist().get(i)){
        			continue;
        		}
        		if(null!=domain.getAccessorylist().get(i).getId())
        		{
        			if(domain.getAccessorylist().get(i).getId().equals(accessory.getId())){
        				isExct=true;
        				break;
        			}
        		}
			}
        	if(!isExct){
				deleteAccessoryList.add(accessory);
			}
        }
        for (int i = 0; i < domain.getAccessorylist().size(); i++) {
        		if(null==domain.getAccessorylist().get(i)){
        			continue;
        		}
        		if(null==domain.getAccessorylist().get(i).getId())
        		{
        			addAccessoryList.add(domain.getAccessorylist().get(i));
        		}
		}
        if(!deleteAccessoryList.isEmpty()){
        	taskFileService.deleteTaskFile(deleteAccessoryList);
        }
        domain.setAccessorylist(addAccessoryList);
        saveAccessory(domain, dto, questions);
        if(ExerciseType.MULTIPLE.getIntValue().equals(domain.getQuestionType()) || ExerciseType.SINGLE.getIntValue().equals(domain.getQuestionType())||ExerciseType.JUDGMENT.getIntValue().equals(domain.getQuestionType())) {
        	updateChoice(domain, dto, questions);
        }
        return questionRespository.save(questions);
    }
    
	private void updateChoice(TaskQuestionDomain domain, AccountDTO dto,
			TaskQuestion questions) {
		//数据库中存储的题目原选项
		List<TaskQuestionChoice> oldChoiceList = taskQuestionChoiceService.getChoiceList(questions.getId());
		HashMap<String,TaskQuestionChoice> oldChoiceMap = new HashMap<String,TaskQuestionChoice>();
		for(TaskQuestionChoice choice : oldChoiceList){
			if(null != choice){
				oldChoiceMap.put(choice.getId(), choice);
			}
		}
		if (null != domain.getChoicelist() && 0 < domain.getChoicelist().size()) {
			List<TaskQuestionChoice> choiceList = new ArrayList<TaskQuestionChoice>();
			TaskQuestionChoice choice = null;
            for (TaskQuestionChoiceDomain choiceDomain : domain.getChoicelist()) {
            	choice = null;
            	if(!choiceDomain.getId().isEmpty()){
            		choice = oldChoiceMap.get(choiceDomain.getId());
            		//更新已存在的题目选项
            		if(null != choice){
            			choice.setOption(choiceDomain.getOption());
    	            	choice.setChoiceContent(choiceDomain.getChoiceContent());
    	            	choice.setTaskQuestionId(questions.getId());
            			choiceList.add(choice);
            			oldChoiceMap.remove(choiceDomain.getId());
            		}else{
            			log.info("当前题目id:"+questions.getId()+",该题目选项id不存在："+choiceDomain.getId());
            		}
            	//新增的题目选项	
            	}else{
	            	choice = new TaskQuestionChoice();
	            	choice.setId(UUID.randomUUID().toString());
	            	choice.setOption(choiceDomain.getOption());
	            	choice.setChoiceContent(choiceDomain.getChoiceContent());
	            	choice.setTaskQuestionId(questions.getId());
	            	choiceList.add(choice);
            	}
            }
            taskQuestionChoiceService.saveChoiceList(choiceList);
        }
		
		//清除已删除的题目选项
		List<TaskQuestionChoice> delChoiceList = new ArrayList<TaskQuestionChoice>();
		for (TaskQuestionChoice choice : oldChoiceMap.values()) {
	          if(null != choice){
	        	  delChoiceList.add(choice);
	          }
		}
		taskQuestionChoiceService.delChoiceList(delChoiceList);
	}

    public TaskQuestion findById(String id) {
        return questionRespository.findByIdAndDeleteFlag(id, DataValidity.VALID.getState());
    }

    public List<TaskQuestion> findByWorkLibIds(List<String> ids) {
        return questionRespository.findByTaskIdInAndDeleteFlag(ids, DataValidity.VALID.getState());
    }

    /**
     * 根据ID查看试题
     * @param questionId
     * @return
     */
    public TaskQuestionDomain findQuestionById(String questionId){
        TaskQuestionDomain taskQuestionDomain = new TaskQuestionDomain();
        TaskQuestion taskQuestion = questionRespository.findOne(questionId);
        BeanUtils.copyProperties(taskQuestion,taskQuestionDomain);
        if(ExerciseType.MULTIPLE.getIntValue().equals(taskQuestionDomain.getQuestionType()) || ExerciseType.SINGLE.getIntValue().equals(taskQuestionDomain.getQuestionType())||ExerciseType.JUDGMENT.getIntValue().equals(taskQuestionDomain.getQuestionType())) {
            taskQuestionDomain.setChoicelist(taskQuestionChoiceService.getChoiceDomainList(DataValidity.VALID.getState(),taskQuestionDomain.getId()));
        }
        List<TaskFile> questionsAccessoryList=taskFileService.findAllByTaskQuestionId(taskQuestion.getId());
        for (TaskFile accessory : questionsAccessoryList) {
            if(accessory.getTaskQuestionId().equals(taskQuestion.getId())){
                TaskFileDomain accessoryDomain = new TaskFileDomain();
                BeanUtils.copyProperties(accessory, accessoryDomain);

                if (accessoryDomain.getSource().equals(TaskInforCode.FILE_FROM_QUESTION)){
                    taskQuestionDomain.getAccessorylist().add(accessoryDomain);
                }
                if (accessoryDomain.getSource().equals(TaskInforCode.FILE_FROM_ANSWER)){
                    taskQuestionDomain.getAccessorylistAnswer().add(accessoryDomain);
                }
                if (accessoryDomain.getSource().equals(TaskInforCode.FILE_FROM_ANALYSIS)){
                    taskQuestionDomain.getAccessorylistAna().add(accessoryDomain);
                }

            }
        }
        return taskQuestionDomain;
    }
    /**
     * 根据试题ID获取试题的第几题
     * @param taskId
     * @param orderNum
     * @return
     */
    public TaskQuestionDomain findQuestionOne(String taskId,Integer orderNum){
        TaskQuestionDomain taskQuestionDomain = new TaskQuestionDomain();
        TaskQuestion taskQuestion = questionRespository.findByTaskIdAndOrderNumAndDeleteFlag(taskId, orderNum, DataValidity.VALID.getState());
        BeanUtils.copyProperties(taskQuestion,taskQuestionDomain);
        if(ExerciseType.MULTIPLE.getIntValue().equals(taskQuestionDomain.getQuestionType()) || ExerciseType.SINGLE.getIntValue().equals(taskQuestionDomain.getQuestionType())||ExerciseType.JUDGMENT.getIntValue().equals(taskQuestionDomain.getQuestionType())) {
            taskQuestionDomain.setChoicelist(taskQuestionChoiceService.getChoiceDomainList(DataValidity.VALID.getState(),taskQuestionDomain.getId()));
        }
        List<TaskFile> questionsAccessoryList=taskFileService.findAllByTaskQuestionId(taskQuestion.getId());
        for (TaskFile accessory : questionsAccessoryList) {
            if(accessory.getTaskQuestionId().equals(taskQuestion.getId())){
                TaskFileDomain accessoryDomain = new TaskFileDomain();
                BeanUtils.copyProperties(accessory, accessoryDomain);

                if (accessoryDomain.getSource().equals(TaskInforCode.FILE_FROM_QUESTION)){
                    taskQuestionDomain.getAccessorylist().add(accessoryDomain);
                }
                if (accessoryDomain.getSource().equals(TaskInforCode.FILE_FROM_ANSWER)){
                    taskQuestionDomain.getAccessorylistAnswer().add(accessoryDomain);
                }
                if (accessoryDomain.getSource().equals(TaskInforCode.FILE_FROM_ANALYSIS)){
                    taskQuestionDomain.getAccessorylistAna().add(accessoryDomain);
                }

            }
        }
        return taskQuestionDomain;
    }
    

    public List<TaskQuestionDomain> findByTaskId(String taskId) {
        List<TaskQuestion> questionslist = questionRespository
                .findByTaskIdAndDeleteFlagOrderByOrderNumAsc(taskId, DataValidity.VALID.getState());
        List<TaskFile>  questionsAccessoryList=taskFileService.findAllByTaskId( taskId);
        List<TaskQuestionDomain> questionsDomainlist = new ArrayList<TaskQuestionDomain>();
        for (TaskQuestion questions : questionslist) {
            TaskQuestionDomain questionsDomain = new TaskQuestionDomain();
            BeanUtils.copyProperties(questions, questionsDomain);
            if(ExerciseType.MULTIPLE.getIntValue().equals(questionsDomain.getQuestionType()) || ExerciseType.SINGLE.getIntValue().equals(questionsDomain.getQuestionType())||ExerciseType.JUDGMENT.getIntValue().equals(questionsDomain.getQuestionType())) {
            	questionsDomain.setChoicelist(taskQuestionChoiceService.getChoiceDomainList(DataValidity.VALID.getState(),questions.getId()));
            }
            for (TaskFile accessory : questionsAccessoryList) {
            	if(questions.getId().equals(accessory.getTaskQuestionId())){
                    TaskFileDomain accessoryDomain = new TaskFileDomain();
                    BeanUtils.copyProperties(accessory, accessoryDomain);
                   
					if (accessoryDomain.getSource().equals(TaskInforCode.FILE_FROM_QUESTION)){
                        questionsDomain.getAccessorylist().add(accessoryDomain);
                    }
					if (accessoryDomain.getSource().equals(TaskInforCode.FILE_FROM_ANSWER)){
                        questionsDomain.getAccessorylistAnswer().add(accessoryDomain);
                    }
					if (accessoryDomain.getSource().equals(TaskInforCode.FILE_FROM_ANALYSIS)){
                        questionsDomain.getAccessorylistAna().add(accessoryDomain);
                    }

            	}
            }
            questionsDomainlist.add(questionsDomain);
        }
        return questionsDomainlist;
    }

//    public ReturnJsonDataV2<List<TaskQuestionDomain>,List<KnowledgeDomainV2>> findWorkReleaseInfo(String workReleaseId){
//        ReturnJsonDataV2<List<TaskQuestionDomain>,List<KnowledgeDomainV2>> returnJsonData =new ReturnJsonDataV2<>();
//       WorkRelease workRelease =  workReleaseService.findById(workReleaseId);
//       if (null!=workRelease&&workRelease.getChapterId()!=null){
//           List<KnowledgeDomainV2> knowledgeDomainV2List =  knowledgeJdbc.findList(workRelease.getChapterId());
//           returnJsonData.setKnowList(knowledgeDomainV2List);
//       }
//       List<TaskQuestionBackup> TaskQuestionBackupList =  TaskQuestionBackupRespository.findAllByWorkReleaseIdAndDeleteFlag(workReleaseId,DataValidity.VALID.getState());
//       List<QusetionsAccessoryBackup> qusetionsAccessoryBackupList  =  qusetionsAccessoryBackupRespository.findByWorkReleaseIdAndDeleteFlag(workReleaseId,DataValidity.VALID.getState());
//       List<EMFile> eMFileList = qusetionAccessoryJdbc.findByWorkReleaseIdAndDeleteFlag(workReleaseId,DataValidity.VALID.getState());
//        List<TaskQuestionDomain> questionsDomainlist = new ArrayList<TaskQuestionDomain>();
//        if (null!=TaskQuestionBackupList) {
//            for (TaskQuestionBackup questions : TaskQuestionBackupList) {
//                TaskQuestionDomain questionsDomain = new TaskQuestionDomain();
//                BeanUtils.copyProperties(questions, questionsDomain);
//                if (ExerciseType.MULTIPLE.getIntValue() == questionsDomain.getQuestionType() || ExerciseType.SINGLE.getIntValue() == questionsDomain.getQuestionType()) {
//                    questionsDomain.setChoicelist(TaskQuestionChoiceBackupService.getChoiceDomainList(DataValidity.VALID.getState(), questions.getId()));
//                }
//                if (null!=qusetionsAccessoryBackupList) {
//                    for (QusetionsAccessoryBackup accessory : qusetionsAccessoryBackupList) {
//                        if (accessory.getQuestionsId().equals(questions.getId())) {
//                            TaskFileDomain accessoryDomain = new TaskFileDomain();
//                            accessoryDomain.setQuestionsId(questions.getId());
//                            accessoryDomain.setFileId(accessory.getFileId());
//                            accessoryDomain.setType(accessory.getType());
//                            if (eMFileList!=null) {
//                                for (EMFile file : eMFileList) {
//                                    if (file.getId().longValue() == accessory.getFileId().longValue()) {
//                                        accessoryDomain.setAccessoryName(file.getName());
//                                        accessoryDomain.setAccessoryUrl(file.getSrcUrl());
//                                        accessoryDomain.setAccessorySwfUrl(file.getSwfUrl());
//                                        accessoryDomain.setAccessorySize(file.getFileSize());
//                                        accessoryDomain.setDocKey(file.getDocKey());
//                                        accessoryDomain.setDocId(file.getDocId());
//                                        accessoryDomain.setDocStatus(file.getDocStatus());
//                                        accessoryDomain.setFileKey(file.getFileKey());
//                                    }
//                                }
//                            }
//                            if (accessoryDomain.getType().equals("1")) {
//                                questionsDomain.getAccessorylist().add(accessoryDomain);
//                            }
//                            if (accessoryDomain.getType().equals("2")) {
//                                questionsDomain.getAccessorylistAnswer().add(accessoryDomain);
//                            }
//                            if (accessoryDomain.getType().equals("3")) {
//                                questionsDomain.getAccessorylistAna().add(accessoryDomain);
//                            }
//
//                        }
//                    }
//                }
//                questionsDomainlist.add(questionsDomain);
//            }
//        }
//
//        returnJsonData.setData(questionsDomainlist);
//        returnJsonData.setCode(200);
//        returnJsonData.setResult(Boolean.TRUE);
//        return returnJsonData;
//    }

    /**
     * @param @param  questions
     * @param @return
     * @return TaskQuestion
     * @throws
     * @Title: upQuestions
     * @Description: 上移试题
     */
    @Transactional
    public TaskQuestion upQuestions(Map<String, Object> result, TaskQuestion questions) {
        TaskQuestion upQuestions = questionRespository.findByTaskIdAndOrderNumAndDeleteFlag(
                questions.getTaskId(), questions.getOrderNum() - 1, DataValidity.VALID.getState());
        if (null != upQuestions) {
            Integer orderNum = questions.getOrderNum();
            questions.setOrderNum(upQuestions.getOrderNum());
            upQuestions.setOrderNum(orderNum);
            questionRespository.save(upQuestions);
            return questionRespository.save(questions);
        } else {
            result.put(ApiReturnConstants.RESULT, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "上移试题失败");
            return null;
        }

    }

    /**
     * @param @param  questions
     * @param @return
     * @return TaskQuestion
     * @throws
     * @Title: downQuestions
     * @Description: 下移试题
     */
    @Transactional
    public TaskQuestion downQuestions(Map<String, Object> result, TaskQuestion questions) {
        TaskQuestion downQuestions = questionRespository.findByTaskIdAndOrderNumAndDeleteFlag(
                questions.getTaskId(), questions.getOrderNum() + 1, DataValidity.VALID.getState());
        if (null != downQuestions) {
            Integer orderNum = questions.getOrderNum();
            questions.setOrderNum(downQuestions.getOrderNum());
            downQuestions.setOrderNum(orderNum);
            questionRespository.save(downQuestions);
            return questionRespository.save(questions);
        } else {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "下移试题失败");
            return null;
        }

    }

    /**
     * @param @param  questions
     * @param @return
     * @return TaskQuestion
     * @throws
     * @Title: delQuestions
     * @Description: 删除试题并更新试题序号
     */
    @Transactional
    public TaskQuestion delQuestions(TaskQuestion questions) {
        taskQuestionJDBC.delOrderNum(questions.getTaskId(), questions.getOrderNum(),questions.getId());
        //删除题目选项
        if(ExerciseType.MULTIPLE.getIntValue().equals(questions.getQuestionType()) || ExerciseType.SINGLE.getIntValue().equals(questions.getQuestionType())) {
	        List<TaskQuestionChoice> choiceList = taskQuestionChoiceService.getChoiceList(questions.getId());
	        for(TaskQuestionChoice choice : choiceList){
	        	choice.setDeleteFlag(DataValidity.INVALID.getState());
	        }
	        taskQuestionChoiceService.saveChoiceList(choiceList);
        }
        Task task = taskService.findById(questions.getTaskId());
        if(null != task.getQuestionsNum()){
        	task.setQuestionsNum(task.getQuestionsNum()-1);
        	taskService.save(task);
        }
        
        return questions;
    }

    public List<TaskQuestion> getListTaskQuestion(String taskId) {
        return questionRespository.findByTaskIdAndDeleteFlagOrderByOrderNumAsc(taskId,DataValidity.VALID.getState());

    }
    public  void save(List<TaskQuestion> taskQuestions){
        questionRespository.save(taskQuestions);
    }
    public Integer countTaskQuestionNum(String taskId,Integer deleteFlag){
        return questionRespository.countByTaskIdAndDeleteFlag(taskId,DataValidity.VALID.getState());
    }
}
